<?php


namespace App\Logic\Product\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Model\Product\ProductModel;
use App\Util\CommonHelper;
use EasySwoole\ORM\DbManager;

class SubmitProductForm extends BaseListForm
{
    public $id;
    public $goods_name;
    public $goods_img;
    public $goods_url;
    public $goods_price;
    public $created_at;

    /**
     * 校验规则 rules
     * @return array[]
     */
    public function rules()
    {
        return [
            'goods_price' => ['required|numeric|min:0.01', '商品单价', '商品单价错误'],
            'goods_name'  => ['required', '商品名称', '商品名称错误'],
            'goods_img'   => ['required', '商品图片', '商品图片错误'],
            'goods_url'   => ['required', '商品链接', '商品链接错误'],
        ];
    }

    public function validate()
    {
        //生成验证器，方法自动读取rules方法返回的值数据
        $validator = $this->createValidator();
        if (!($check = $validator->validate($this->getAttributes()))) {
            throw new DefaultException($validator->getError()->__toString(), 600);
        }
        return true;
    }

    public function submit()
    {
        $this->validate();
        //插入数据
        DbManager::getInstance()->startTransactionWithCount('write');
        try {
            //添加表
            $insertData = [
                'goods_name'  => $this->goods_name,
                'goods_img'   => $this->goods_img,
                'goods_price' => $this->goods_price,
                'goods_url'   => $this->goods_url,
                'created_at'  => date('Y-m-d H:i:s'),
            ];

            //插入数据库
            $res = ProductModel::insertData($insertData);
            $id  = $res->lastQueryResult()->getLastInsertId();

            DbManager::getInstance()->commitWithCount('write');

            $returnData = ['id' => $id];

            $result = $this->success($returnData);
            return $result;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '添加商品错误');
            throw $e;
        }
    }
}
